import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    fruits: [
      { id: 1, name: 'apple', price: 10 },
      { id: 2, name: 'banana', price: 20 },
      { id: 3, name: 'orange', price: 30 }
    ],
    cart: []
  },
  getters: {
    getFruitById: (state) =>{
        return (id) => {
           return state.fruits.find(fruit => fruit.id === id);
        }
    },
    cartItems: state => state.cart,
    cartTotal: state => {
      return state.cart.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    }
  },
  mutations: {
    addFruit(state, fruit) {
        state.fruits.push(fruit);
    },
    addToCart(state, { id, quantity }) {
      const record = state.cart.find(item => item.id === id);
      if (record) {
        record.quantity += quantity;
      } else {
        const fruit = state.fruits.find(fruit => fruit.id === id);
        state.cart.push({
          ...fruit,
          quantity
        });
      }
    },
    removeFromCart(state, id) {
      state.cart = state.cart.filter(item => item.id !== id);
    },
    updateQuantity(state, { id, quantity }) {
      const record = state.cart.find(item => item.id === id);
      if (record) {
        record.quantity = quantity;
      }
    }
  },
  actions: {
    addToCart({ commit }, payload) {
      commit('addToCart', payload);
    },
    removeFromCart({ commit }, id) {
      commit('removeFromCart', id);
    },
    updateQuantity({ commit }, payload) {
      commit('updateQuantity', payload);
    }
  },
  modules: {
  }
})
